import { Lang } from 'quasar'
import { defineBoot } from '#q-app/wrappers'
import messages from 'src/i18n'
// import { getStore } from 'src/utils/storage'
import { createI18n } from 'vue-i18n'

const i18nPackage = {
  'zh-CN': { suffixName: 'ZhCn', nativeName: '中文(简体)' },
  'en-US': { suffixName: 'EnUs', nativeName: 'English (US)' }
}
// const findLanguage = lang => {
//   for (const key in i18nPackage) {
//     if (key === lang || lang.startsWith(key) || key.startsWith(lang)) return key
//   }
//   return 'zh-CN'
// }
// let lang = getStore('locale', 'L') || navigator.language || navigator.browserLanguage
// if (!supportedLanguages.includes(lang)) lang = findLanguage(lang)

const lang = 'zh-CN'
const remotePlugin = async locale => {
  const langModule = await import(`app/node_modules/quasar/lang/${locale}.js`) || {}
  Lang.set(langModule.default || langModule)
}

const i18n = createI18n({ locale: lang, messages, globalInjection: true, legacy: false })
export default defineBoot(({ app }) => app.use(i18n) && remotePlugin(lang))
const i18nJs = i18n.global

/**
 * 字段名转换i18n
 */
const toI18nName = fieldName => {
  const i18nSuffix = i18nPackage[i18nJs.locale.value]?.suffixName || 'EnUs'
  return `${fieldName.substring(0, fieldName.length - 4)}${i18nSuffix}`
}
/**
 * Quasar语言包切换
 */
const toggleLanguage = locale => i18nJs.locale.value !== locale && remotePlugin(locale)

export { i18nJs as i18n, i18nPackage, toggleLanguage, toI18nName }